package com.fingard.dsp.bank.directbank.abc01;

import com.fingard.client.DspClient;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.helpers.FileType;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.TcpReceiver;
import com.fingard.text.MFSHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

/**
 * 中国农业银行银企直联专线版(ABC01)历史明细查询
 */
public class ABC01Transaction extends ABC01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();

        String tmpRespCode = "";
        String tmpRespInfo = "";

        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }

                ABC01Header bankHeader = new ABC01Header();
                bankHeader.reqSeqID = p_req7516.reqHeader.transSeqID;
                bankHeader.transCode = ABC01TransCode.deal_7516or7515;

                XmlTextWriter xmlWriter = new XmlTextWriter();
                writeCommonHead(xmlWriter, bankHeader);

                xmlWriter.writeStartElement("Cmp");
                String dbProv = p_req7516.actArea;
                if ("true".equals(getBankConfig().getValueAsString("useActInfoSetOwnerArea").toLowerCase())) {
                    if ((p_req7516.actNum.indexOf('-') > 0 && p_req7516.actNum.length() == 18) || (p_req7516.actNum.length() == 17)) {
                        dbProv = p_req7516.actNum.substring(0, 2);
                    }
                }
                xmlWriter.writeElementString("DbProv", dbProv);
                xmlWriter.writeElementString("DbAccNo", getAbcAccNo(p_req7516.actNum));
                xmlWriter.writeElementString("DbCur", convertCurToBank(p_req7516.actCur));
                xmlWriter.writeElementClosed("StartTime");
                xmlWriter.writeEndElement();

                xmlWriter.writeStartElement("Corp");
                xmlWriter.writeElementString("StartDate", Format.Date8Format.format(tmpCalendarFrom.getTime()));
                xmlWriter.writeElementString("EndDate", Format.Date8Format.format(tmpClndrStepTo.getTime()));
                xmlWriter.writeEndElement();

                xmlWriter.writeStartElement("Channel");
                xmlWriter.writeElementString("LastJrnNo", "0");
                xmlWriter.writeEndElement();
                xmlWriter.writeEndDocument();

                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
//                String[] tmpStrRet = new String[]{"", FileHelper.readToString(new File("E:\\5_docs\\4_DSP\\通威\\ABC01\\a.txt"), "utf-8")};
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/ap/RespCode");
                        String tmpRetInfo = tmpBkReader.getFirstText("/ap/RespInfo");
                        String tmpRetRxtInfo = tmpBkReader.getFirstText("/ap/RxtInfo");
                        if ("0000".equals(tmpRetCode)) {
                            int tmpRecordNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/Cme/RecordNum"));
                            int tmpFieldNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/Cme/FieldNum"));
                            if (tmpRecordNum > 0) {
                                String tmpDataMFS = null;
                                String tmpFileFlag = tmpBkReader.getFirstText("/ap/FileFlag");
                                if ("1".equals(tmpFileFlag)) {
                                    String tmpBatchFileName = tmpBkReader.getFirstText("/ap/Cmp/BatchFileName");
                                    String tmpFilePath = StringHelper.trimEnd(bankFront.bkTransFolder, File.separator) + File.separator + tmpBatchFileName;
                                    WriteBankLogLn2("前置机历史明细结果文件路径：" + tmpFilePath);
                                    if ("dspfileserver".equals(this.bankFront.getAccessBkFileModeLowerCase())) {
                                        WriteBankLogLn("accessBkFileMode：" + bankFront.accessBkFileMode);
                                        DspClient dspClient = new DspClient(bankFront.dspFileServer);
                                        dspClient.charsetName = getCharset();
                                        TcpReceiver tcpRec = dspClient.getFile(FileType.bankFile, tmpFilePath);
                                        if (tcpRec.isCompleted) {
                                            if (tcpRec.isRtnBinaryFile) {
                                                tmpDataMFS = new String(tcpRec.recBytes, tcpRec.contentStartIndex, tcpRec.contentLength, tcpRec.charsetName);
                                            } else {
                                                String errMsg = new String(tcpRec.recBytes, tcpRec.contentStartIndex, tcpRec.contentLength, tcpRec.charsetName);
                                                WriteBankLogLn("从远程DSP（" + bankFront.dspFileServer + "）获取前置文件未完成：" + errMsg);
                                            }
                                        } else {
                                            this.WriteBankLogLn("从远程DSP（" + bankFront.dspFileServer + "）获取前置文件未完成：" + tcpRec.getConnMsg());
                                        }
                                    } else {
                                        tmpDataMFS = FileHelper.readFileText(tmpFilePath, getCharset());
                                    }
                                    if (tmpDataMFS == null) {
                                        WriteBankLogLn("读取前置数据文件返回为null，需确认前置文件夹配置和文件是否存在");
                                    } else {
                                        WriteBankLogStep3(tmpDataMFS);
                                    }
                                } else {
                                    tmpDataMFS = tmpBkReader.getFirstText("/ap/Cmp/RespPrvData");
                                }
                                if (tmpDataMFS != null) {
                                    StringBuilder tmpSbLog = new StringBuilder();
                                    ArrayList<String[]> tmpArrayList;
                                    if (tmpDataMFS.startsWith("Prov")) {
                                        tmpArrayList = MFSHelper.getTextArray(tmpDataMFS, "|", tmpFieldNum, tmpRecordNum + 1, tmpSbLog);
                                    } else {
                                        tmpArrayList = MFSHelper.getTextArray(tmpDataMFS, "|", tmpFieldNum, tmpRecordNum, tmpSbLog);
                                    }
                                    if (tmpSbLog.length() == 0) {
                                        for (int i = 0; i < tmpArrayList.size(); i++) {
                                            String[] tmpEachArr = tmpArrayList.get(i);
                                            //发生额标志(21) 0正常  1红字  2蓝字 3已抹 4抹帐
                                            if (tmpEachArr[9].equals("0") || tmpEachArr[9].equals("1") || tmpEachArr[9].equals("2")) {
                                                RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                                tmpRetDetail.actArea = tmpEachArr[0].trim();
                                                tmpRetDetail.actNum = tmpEachArr[1].trim();
                                                tmpRetDetail.cur = this.convertCurToATS(tmpEachArr[2]);

                                                String tmpRecBank = StringHelper.convertToDBC(tmpEachArr[14]).trim();
                                                tmpRetDetail.recAccBank = tmpRecBank;

                                                boolean jionBkArea7516 = getBankConfig().getValueAsBool("jionBkArea7516");
                                                if (tmpRecBank.contains("中国农业银行") && jionBkArea7516 && StringHelper.hasAnyChar(tmpEachArr[10])) {
                                                    tmpRetDetail.recAccNum = tmpEachArr[10].trim() + tmpEachArr[11].trim();
                                                } else {
                                                    tmpRetDetail.recAccNum = tmpEachArr[11].trim();
                                                }
                                                tmpRetDetail.recAccName = tmpEachArr[13].trim();
                                                if (tmpEachArr[22].startsWith("-")) {
                                                    tmpRetDetail.cdFlag = "1";
                                                    if (tmpEachArr[9].equals("1") || tmpEachArr[9].equals("2")) {
                                                        tmpRetDetail.cdFlag = "2";
                                                    }
                                                } else {
                                                    tmpRetDetail.cdFlag = "2";
                                                    if (tmpEachArr[9].equals("1") || tmpEachArr[9].equals("2")) {
                                                        tmpRetDetail.cdFlag = "1";
                                                    }
                                                }
                                                tmpRetDetail.tranAmt = tmpEachArr[22].replace("-", "");
                                                if (tmpEachArr[3].length() == 8) {
                                                    tmpRetDetail.tranDate = tmpEachArr[3].substring(0, 4) + "-" + tmpEachArr[3].substring(4, 6) + "-" + tmpEachArr[3].substring(6, 8);
                                                } else {
                                                    tmpRetDetail.tranDate = tmpEachArr[3];
                                                }
                                                if (tmpEachArr[4].length() >= 14) {
                                                    tmpRetDetail.tranTime = tmpEachArr[4].substring(0, 4) + "-" + tmpEachArr[4].substring(4, 6) + "-" + tmpEachArr[4].substring(6, 8) + " " + tmpEachArr[4].substring(8, 10) + ":" + tmpEachArr[4].substring(10, 12) + ":" + tmpEachArr[4].substring(12, 14);
                                                } else {
                                                    tmpRetDetail.tranTime = tmpEachArr[4];
                                                }
                                                tmpRetDetail.valueDate = tmpRetDetail.tranDate;
                                                tmpRetDetail.postTimestamp = tmpEachArr[4];
                                                tmpRetDetail.accBal = tmpEachArr[23];
                                                tmpRetDetail.billType = tmpEachArr[27];
                                                tmpRetDetail.billNum = tmpEachArr[34];
                                                nodeAnalysic(tmpEachArr, tmpRetDetail, getCharset());
                                                String comment = tmpEachArr[35];
                                                boolean useNewComment = getBankConfig().getValueAsBool("useNewComment");
                                                WriteBankLogLn("useNewComment:" + useNewComment);
                                                if (useNewComment) {
                                                    comment = getBankConfig().getMapValueByKey("commentMapping", comment);
                                                }
                                                tmpRetDetail.comment = comment;
                                                tmpRetDetail.originator = tmpEachArr[33];
                                                tmpRetDetail.payCode = StringHelper.joinNotEmpty("+", tmpEachArr[32], tmpEachArr[30], tmpEachArr[31]);
                                                nodeAnalysic(tmpEachArr, tmpRetDetail, getCharset());
                                                retAts.writeRetDetail(tmpRetDetail);
                                            }
                                        }
                                    } else {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = tmpSbLog.toString();
                                    }
                                } else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "数据为空";
                                }
                            }
                        } else if (!"查询无数据!".equals(tmpRetRxtInfo)) {
                            tmpRespCode = "-1";
                            if (!StringHelper.isNullOrEmpty(tmpRetRxtInfo)) {
                                tmpRespInfo = tmpRetRxtInfo;
                            } else {
                                tmpRespInfo = tmpRetInfo;
                            }
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpStrRet[1];
                    break;
                }

                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        if ("-1".equals(tmpRespCode)) {
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空!");
        }

        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);

        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;

        String tmpDateNow = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpDateNow;
        tmpReq7516.dateTo = tmpDateNow;

        return d_7516_HisTrans(tmpReq7516);
    }
}